<?php

class LoginController extends Zend_Controller_Action
{
	
	public function preDispatch()
	{
		if (Zend_Auth::getInstance()->hasIdentity()) {
			// If the user is logged in, we don't want to show the login form;
			// however, the logout action should still be available
			if ('logout' != $this->getRequest()->getActionName()) {
				$this->_helper->redirector('index', 'index');
			}
		} else {
			// If they aren't, they can't logout, so that action should
			// redirect to the login form
			if ('logout' == $this->getRequest()->getActionName()) {
				$this->_helper->redirector('index');
			}
		}
	}
	
	public function indexAction()
	{

               /* $galleryElementModel = new Application_Model_ActivityModel();
                $condition = "start_date <= now()";

                $auth = Zend_Auth::getInstance();
                $user = $auth->getIdentity();
                $conditionUser = "user_id".$user->idusers;
                
                $select = $galleryElementModel->select()->where($condition);
                print_r();*/
		$this->view->form = $this->getForm();
                //$this->view->actividades = $select->getAdapter()->fetchAll();
                
	}
        
        public function registerAction()
	{
            $request = $this->getRequest();
            $form = new Application_Form_RegisterForm();
            
            if ($request->isPost()) {
                    if ($form->isValid($request->getPost())) {

                            $data = $form->getValues();
                            
                            $id = $this->saveUserWithValues($data);
                            
                            $fileName = $form->userPhoto->getFileName();
                            $fileExtension = $this->getFileExtension($fileName);

                            $newFileName = "photo_$id.$fileExtension";
                            $photoPath = APPLICATION_PATH . "/../public/uploads/$newFileName";
                            $photoURL = 'http://'.$_SERVER['SERVER_NAME'] . $this->getRequest()->getBaseUrl() . '/uploads/' . $newFileName;
                            // Traemos el adapter de Zend_File_Transfer
                            $upload = $form->userPhoto->getTransferAdapter();
                            $this->renameFile($upload, $photoPath);
                            
                            $userToUpdate = array(
                                "photo_url" => $photoURL
                            );
                            
                            $userModel = new Application_Model_UserModel();
                            $userModel->update($userToUpdate, "idusers=$id");
                            
                            return $this->_helper->redirector('index', 'index');
                    }
            }

            $this->view->form = $form;
	}



        public function saveUserWithValues($data) {
            $userModel = new Application_Model_UserModel();

            $userToSave = array();
            $userToSave["username"] = $data["username"];
            $userToSave["password"] = $data["password"];
            $userToSave["age"] = $data["age"];
            $userToSave["latitude"] = $data["latitude"];
            $userToSave["longitude"] = $data["longitude"];

            return $userModel->insert($userToSave);
	}

        public function getFileExtension($fileName) {
		$filenamePathInfo = pathinfo($fileName);
		return $filenamePathInfo['extension'];
	}
        
        public function renameFile($upload, $galleryElementPath) {		
		// Lo ideal es que el path lo trajeramos de un archivo de configuracion.
		$upload->addFilter('Rename', array(
		                        'target' => $galleryElementPath,
		                        'overwrite' => true
		));
		var_dump( $upload->receive() );
	}
	
	public function getForm()
	{
		return new Application_Form_LoginForm();
	}

	public function processAction()
	{
		$request = $this->getRequest();
		
		// Check if we have a POST request
		if (!$request->isPost()) {
			return $this->_helper->redirector('index');
		}
		
		// Get our form and validate it
		$form = $this->getForm();
		if (!$form->isValid($request->getPost())) {
			// Invalid entries
			$this->view->form = $form;
			$form->setAction("process");
			return $this->render('index'); // re-render the login form
		}
		
		// Get our authentication adapter and check credentials
		$adapter = $this->getAuthAdapter($form->getValues());
		$auth = Zend_Auth::getInstance();
		$result  = $auth->authenticate($adapter);
		if (!$result->isValid()) {
			// Invalid credentials
			$form->setDescription('Invalid credentials provided');
			$this->view->form = $form;
			$form->setAction("process");
			return $this->render('index'); // re-render the login form
		} else {
			$storage = new Zend_Auth_Storage_Session();
			$storage->write($adapter->getResultRowObject());
		}		
		
		// We're authenticated! Redirect to the home page
		$this->_helper->redirector('index', 'index');
	}
	
	public function getAuthAdapter(array $params)
	{
		// Leaving this to the developer...
		// Makes the assumption that the constructor takes an array of
		// parameters which it then uses as credentials to verify identity.
		// Our form, of course, will just pass the parameters 'username'
		// and 'password'.
		$userModel = new Application_Model_UserModel();
		$authAdapter = new Zend_Auth_Adapter_DbTable($userModel->getAdapter(), "users");
		$authAdapter->setCredentialColumn("username");
		$authAdapter->setIdentityColumn("password");
		$authAdapter->setCredential($params["username"]);
		$authAdapter->setIdentity($params["password"]);
		return $authAdapter;
	}
	
	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_helper->redirector('index'); // back to login page
	}
	
}